package com.demo.forum.controller;

import com.demo.forum.common.Result;
import com.demo.forum.common.ResultCode;
import com.demo.forum.config.AppConfig;
import com.demo.forum.model.Article;
import com.demo.forum.model.Board;
import com.demo.forum.model.User;
import com.demo.forum.model.exception.ApplicationException;
import com.demo.forum.services.IArticleService;
import com.demo.forum.services.IBoradService;
import com.demo.forum.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/article")
@Api(tags = "文章接口 ")
public class ArticleController {
    @Autowired
    private IBoradService boradService;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private IUserService userService;

    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public Result create(HttpServletRequest request ,
                       @ApiParam("版块Id") @RequestParam("boardId") @NonNull Long boardId,
                       @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                       @ApiParam("文章内容") @RequestParam("content") @NonNull String content){

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_LOGUN);
        if(user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_BANNED));
        }
        Board board = boradService.selectById(boardId);
        if(board == null || board.getDeleteState() == 1 || board.getState() == 1){
            log.error(ResultCode.FAILED_BOARD_BANNED.toString());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_BOARD_BANNED)
                    + ", boardId = " + boardId);
        }
        Article article = new Article();
        article.setUserId(user.getId());
        article.setBoardId(boardId);
        article.setContent(content);
        article.setTitle(title);
        articleService.create(article);
        return Result.success();

    }


    @ApiOperation("获取文章")
    @GetMapping("/getAllByBoardId")
    public Result<List<Article>> getAllByBoardId(@ApiParam("板块id") @RequestParam(value = "boardId" , required = false) Long boardId){
        List<Article> articles = null;
        if(boardId == null){
            articles = articleService.selectAll();
        }else{
            articles = articleService.selectAllByBordId(boardId);
        }
        if(articles == null){
            articles = new ArrayList<>();

        }

        return Result.success(articles);



    }

    /**
     * 根据帖子id 获取帖子详情
     * @param id
     * @return
     */
    @GetMapping("/details")
    @ApiOperation("获取帖子详情")
    public Result details( HttpServletRequest request,
            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_LOGUN);
        Article article = articleService.selectDetailById(id);
        if(article == null) {
            return Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(user.getId() == article.getUserId()){
            article.setOwn(true);

        }

        return Result.success(article);

    }

    @PostMapping("/modify")
    @ApiOperation("更新帖子")
    public Result modify(HttpServletRequest request,
            @RequestParam("id") @ApiParam("帖子id") @NonNull Long id,
                         @RequestParam("title") @ApiParam("帖子标题") @NonNull String title,
                         @RequestParam("content") @ApiParam("帖子正文") @NonNull String content){
      //判断用户是否被禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_LOGUN);
        if(user.getState() == 1 ){
            return Result.failed(ResultCode.FAILED_USER_BANNED);
        }
        //判断帖子是否存在
        Article article = articleService.selectById(id);
        if(article == null ){
            return Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断帖子的作者id 是否和登录id 相同
        if(user.getId() != article.getUserId()){
            return Result.failed(ResultCode.FAILED_FORBIDDEN);
        }

        //判断帖子是否可以修改
        if(article.getDeleteState() == 1 || article.getState() ==1 ){
            return Result.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        articleService.modify(id,title,content);
        log.info("帖子更新成功. Article id = " + id + "User id = " + user.getId() + ".");
        return Result.success();
    }

    @ApiOperation("点赞操作")
    @PostMapping("/thumbsUp")
    public Result thumbsUp( HttpServletRequest request,
            @RequestParam("id") @ApiParam("帖子id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user =(User) session.getAttribute(AppConfig.USER_LOGUN);
        if (user.getState() == 1) {
            // 返回结果
            return Result.failed(ResultCode.FAILED_USER_BANNED);
        }
//        Article article = articleService.selectById(id);
//        if(article == null || article.getDeleteState() == 1){
//            return Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
//        }
//        if(article.getState() == 1){
//            return Result.failed(ResultCode.FAILED_ARTICLE_BANNED);
//        }
//        if(user.getId() != article.getUserId()){
//            return Result.failed(ResultCode.FAILED_FORBIDDEN);
//        }

        articleService.thumbsUp(id);
        return Result.success();

    }

    /**
     *
     * @param id
     * @return
     */
    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public Result delete(HttpServletRequest request,
            @RequestParam("id") @ApiParam("帖子id") @NonNull Long id){
        //判断用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_LOGUN);
        if( user.getState() == 1){
            return Result.failed(ResultCode.FAILED_USER_BANNED);
        }
        //判断帖子状态
        Article article = articleService.selectById(id);
        if(article == null || article.getDeleteState() == 1 ){
            return Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);

        }
        //判断是否是作者
        if(user.getId() != article.getUserId()){
            return Result.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        articleService.delete(id);
        return Result.success();
    }

    @ApiOperation("获取用户的帖子列表")
    @GetMapping("/getAllByUserId")
    public Result<List<Article>> getAllByUserId(HttpServletRequest request,
                                                @ApiParam("用户id") @RequestParam(value = "userId" ,required = false) Long userId){

        if(userId == null){
            HttpSession session = request.getSession(false);
            User user = (User)session.getAttribute(AppConfig.USER_LOGUN);
            userId = user.getId();
        }
        User user = userService.selectById(userId);
        if(user == null){
            return Result.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        List<Article> articles = articleService.selectByUserId(userId);
        return Result.success(articles);


    }



}
